import bean.DiffNodeMap;
import bean.MagneticNode;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class MagneticFileDemo {

    private static List<String> dataList;
    private static final String path = "G:\\GoogleDisk\\post_data\\sensor_data";
    private static List<MagneticNode> nodeList;
    private static double dist[];
    private static final String filePath = System.getProperty("user.dir")+"\\src" +  "\\result\\";

    public static void main(String[] args) throws IOException {

        dataList = new ArrayList<>();
        nodeList = new ArrayList<>();

        File directory = new File(path);
        File directoryList[] = directory.listFiles();
        int n = directoryList.length;
        if (n > 0) {
            for (File aDirectoryList : directoryList) {
                dataList.add(aDirectoryList + "\\magnetic.txt");
            }
        }
        for (int i = 0; i < n; i++) {
            String content = getContent(dataList.get(i));
            contentHandler(content);
        }

        String avgPath = filePath + FilesHandler.getTime() + ".txt";
        //此时已经将各个指纹点的信息放入了nodeList中
        for (int i = 0; i < n; i++) {
            System.out.println(nodeList.get(i).toString());
            MagneticNode node = nodeList.get(i);
            String builder = String.valueOf(node.getLocX()) + "," +
                    String.valueOf(node.getLocY()) + "," +
                    String.valueOf(node.getMagX()) + "," +
                    String.valueOf(node.getMagY()) + "," +
                    String.valueOf(node.getMagZ());
            writeContent(builder, avgPath);
        }

        Scanner in = new Scanner(System.in);
        double x = in.nextDouble();
        double y = in.nextDouble();
        double z = in.nextDouble();
        dist = new double[n];
        for (int i = 0; i < n; i++) {
            dist[i] = Math.sqrt(Math.pow(x - (nodeList.get(i).getMagX()), 2) + Math.pow(y - (nodeList.get(i).getMagY()), 2) + Math.pow(z - (nodeList.get(i).getMagZ()), 2));
        }
        double min = dist[0];
        int k = 0;
        for (int i = 0; i < dist.length; i++) {
            if (min > dist[i]) {
                k = i;
                min = dist[i];
            }
        }
        System.out.println("预测坐标为：" + nodeList.get(k).getLocX() + "," + nodeList.get(k).getLocY());
    }

    /**
     * 获取文件内容
     * @param path 文件路径
     * @return String形式的文件内容
     */
    private static String getContent(String path) {
        StringBuilder builder = new StringBuilder();
        try {
            String encoding="UTF-8";
            File file=new File(path);
            if(file.isFile() && file.exists()){ //判断文件是否存在
                InputStreamReader read = new InputStreamReader(new FileInputStream(file),encoding);//考虑到编码格式
                BufferedReader bufferedReader = new BufferedReader(read);

                String lineTxt;
                int count = 0;
                while((lineTxt = bufferedReader.readLine()) != null){
                    count++;
                    lineTxt = count + "," + lineTxt + "\n";
                    builder.append(lineTxt);
                }
                read.close();
            }else{
                System.out.println("找不到指定的文件");
            }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
            e.printStackTrace();
        }
        return builder.toString();
    }

    /**
     * 根据单个文件的内容生成当前点的地磁平均值
     * @param content 读取的文件内容
     */
    private static void contentHandler(String content) {
        String splitContent[] = content.split("\n");
        int n = splitContent.length;
        String getLoc[] = splitContent[0].split(",");
        MagneticNode node = new MagneticNode();
        node.setDirection(getLoc[1]);
        node.setLocX(Integer.parseInt(getLoc[2]));
        node.setLocY(Integer.parseInt(getLoc[3]));
        double xSum = 0, ySum = 0, zSum = 0;
        for (int i = 1; i < n; i++) {
            String dataDetails[] = splitContent[i].split(",");
            xSum = Double.parseDouble(dataDetails[1]) + xSum;
            ySum = Double.parseDouble(dataDetails[2]) + ySum;
            zSum = Double.parseDouble(dataDetails[3]) + zSum;
        }
        node.setMagX(xSum / (n - 1));
        node.setMagY(ySum / (n - 1));
        node.setMagZ(zSum / (n - 1));
        nodeList.add(node);
    }

    /**
     * 创建一个txt文件并向其中写入得到的平均值结果
     * @param content 文件每行内容
     * @param filePath 文件路径
     */
    private static void writeContent(String content, String filePath) {
        FileWriter writer = null;
        try {
            writer = new FileWriter(filePath, true);
            writer.write(content + "\r\n");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(writer != null){
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}